package com.smartcommunity.controller.facelib;

import com.smartcommunity.faceengine.FaceEngineService;
import com.smartcommunity.bean.model.Result;
import com.smartcommunity.controller.BaseController;
import com.smartcommunity.entity.facelib.sensenets2.SenseNets2FaceDetect;
import com.smartcommunity.entity.facelib.sensenets2.SenseNets2FaceResponse;
import com.smartcommunity.log.interceptor.Log;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @version V1.0
 * @ClassName: FaceEngineController
 * @Description: 人脸引擎相关的接口服务
 * @author: tianzongbing
 * @Date: 2020/02/26
 * @Company:
 */
@RestController
@RequestMapping(value = "/faceEngine")
@Api(value = "人脸特征提取", tags = "人脸特征提取")
@Slf4j
public class FaceEngineController extends BaseController {

    @Autowired
    private FaceEngineService faceEngineService;

    @PostMapping(value="/detect/json")
    @Log(info = "提取人脸特征",module = "人脸特征管理",function = "提取")
    @ApiOperation(value = "提取人脸特征", notes = "提取人脸特征。引擎代理接口，请求与响应的格式与深网2.0引擎接口一致。关键字: POST、JSON、人脸特征")
    public Result<SenseNets2FaceResponse> detectFeatureInJson(@Valid @RequestBody SenseNets2FaceDetect faceLib) {
        try {
            Assert.notNull(faceLib,"查询对象不能为NULL");

            return faceEngineService.detectFaceFeature(faceLib);
        } catch (Exception e) {
            log.error("提取人脸特征错误",e);
            return Result.error(500, getExceptionMessage(e));
        }
    }

    @GetMapping(value="/detect")
    @Log(info = "提取人脸特征",module = "人脸特征管理",function = "提取")
    @ApiOperation(value = "提取人脸特征", notes = "提取人脸特征。参数作图片URL，只提取特征码，不拿结构化属性(年龄、性别、口罩、帽子、眼镜等)。响应格式与深网2.0引擎接口一致。关键字: GET、人脸特征")
    public Result<SenseNets2FaceResponse> detectFeatureByUri(@RequestParam("imgUri") String imgUri) {
        try {
            Assert.hasText(imgUri,"查询图片URI地址不能为空");

            return faceEngineService.detectFaceFeature(imgUri);
        } catch (Exception e) {
            log.error("提取人脸特征错误",e);
            return Result.error(500, getExceptionMessage(e));
        }
    }

    // ------- 工具方法 -------

    /**
     * 获取根异常的描述信息
     * @param e 异常对象
     * @return 根异常的
     */
    static String getExceptionMessage(Exception e) {
        return FaceLibController.getExceptionMessage(e);
    }
}
